//
//  MPRequest.m
//  SearchPeople
//
//  Created by zk on 16/5/10.
//
//

#import "MPRequest.h"
#import <AFNetworking.h>
#import <SVProgressHUD.h>

@interface MPRequest() {
    AFHTTPRequestOperation *opera;
}

@property (assign, nonatomic) BOOL isManualCancel; //是否为手动取消  默认为no

@end

@implementation MPRequest

#pragma mark - init 

- (id)init{
    self = [super init];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)initialize{
    //数据初始化
    self.params = [[NSMutableDictionary alloc] init];
    self.isManualCancel = NO;
    self.showErrorMsg = YES;
}

- (void)startRequestWithSuccessBlock:(MPRequestCompletedBlock)successBlock
                     WithFailedBlock:(MPRequestCompletedBlock)failedBlock{
    
    opera = [[AFHTTPRequestOperation alloc] initWithRequest:self.urlRequest];
    
    __block MPRequest *blockSelf = self;
    
    //开始请求
    [opera setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [blockSelf processSuccessBlockWithOperation:operation
                                 WithResponseObject:responseObject
                                   WithSuccessBlock:successBlock
                                    WithFailedBlock:failedBlock];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [blockSelf processFailureBlockWithOperation:operation WithError:error WithFailedBlock:failedBlock];
    }];
    
    [opera start];
}

- (void)cancelRequest {
    self.isManualCancel = YES;
    [opera cancel];
}

#pragma mark - Process Data 
- (void)processSuccessBlockWithOperation:(AFHTTPRequestOperation *)operation
                      WithResponseObject:(id)ResponseObject
                        WithSuccessBlock:(MPRequestCompletedBlock )successBlock
                         WithFailedBlock:(MPRequestCompletedBlock )failedBlock {
    
    //处理成功时的请求
    NSMutableDictionary *responseData = [NSMutableDictionary dictionary];
    
    @try {
        responseData = [NSJSONSerialization JSONObjectWithData:ResponseObject options:0 error:nil];
    } @catch (NSException *exception) {
        [SVProgressHUD showErrorWithStatus:DATA_FORMAT_ERROR];
    }
    
    MPResponse *response = [[MPResponse alloc] init];
    response.responseName = [NSString stringWithFormat:@"%@响应",self.requestName];
    [response loadResultData:responseData];
    
    if (response.isSuccess == YES) {
        //请求成功
        if (response.result == nil) {
            [SVProgressHUD showSuccessWithStatus:response.errorMsg];
        }
        successBlock(self, response);
    } else {
        //请求失败  自动输出错误信息
        if (self.isShowErrorMsg) {
            if (response.errorMsg) {
                [SVProgressHUD showErrorWithStatus:response.errorMsg];
            } else {
                [SVProgressHUD showErrorWithStatus:DATA_FORMAT_ERROR];
            }
        }
        failedBlock(self, response);
    }
    
}

- (void)processFailureBlockWithOperation:(AFHTTPRequestOperation *)operation
                               WithError:(NSError *)error
                         WithFailedBlock:(MPRequestCompletedBlock )failedBlock {
    
    MPResponse *response = [[MPResponse alloc] initWithResponseDic:nil];
    response.responseName = [NSString stringWithFormat:@"%@响应",self.requestName];
    
    //手动取消的不弹出错误
    if (self.isManualCancel == NO && self.isShowErrorMsg == YES) {
        [SVProgressHUD showErrorWithStatus:REQUEST_FAILE];
    } else {
        [SVProgressHUD dismiss];
    }
    
    failedBlock(self,response);
}

#pragma mark -

-(NSString *)description{
    
    NSMutableString *descripString = [NSMutableString stringWithFormat:@""];
    [descripString appendString:@"\n========================Request Info==========================\n"];
    [descripString appendFormat:@"Request Name:%@\n",self.requestName];
    [descripString appendFormat:@"Request Url:%@\n",self.requestPath];
    [descripString appendFormat:@"Request Methods:%@\n",[self.urlRequest HTTPMethod]];
    [descripString appendFormat:@"Request params:\n%@\n",self.params];
    [descripString appendString:@"===============================================================\n"];
    return descripString;
}


@end
